#!/bin/bash

# 是否需要开启SSL
open_ssl=${OPEN_SSL:-false}

# 设置日志格式
log_format=${LOG_FORMAT:-default}

# 是否开启默认的健康检查服务
enable_health_check=${ENABLE_HEALTH_CHECK:-true}

# 设置默认端口
if [ -n "$CUSTOM_PORT" ]; then
    default_port=$CUSTOM_PORT
elif [ "$open_ssl" = "true" ]; then
    default_port=443
else
    default_port=80
fi

# 初始化分组数组
server_names=()
server_proxy_hosts=()
server_ports=()
valid_groups=()

# 获取匹配的环境变量
server_vars=$(env | grep -E '^SERVER_(NAME|PROXY_HOST|PORT)_')

# 解析环境变量并提取标识符
while IFS= read -r var; do
    key=$(echo "$var" | awk -F'[=]' '{print $1}' | sed -E 's/^SERVER_(NAME|PROXY_HOST|PORT)_//')  # 提取标识符
    name=$(echo "$var" | cut -d '=' -f 1)                                                       # 变量名
    value=$(echo "$var" | cut -d '=' -f 2-)                                                     # 变量值
    if [[ $name == SERVER_NAME* ]]; then
        server_names+=("$key:$value")
    elif [[ $name == SERVER_PROXY_HOST* ]]; then
        server_proxy_hosts+=("$key:$value")
    elif [[ $name == SERVER_PORT* ]]; then
        server_ports+=("$key:$value")
    fi
done <<< "$server_vars"

# 检查并保存有效分组
for key in $(printf "%s\n" "${server_names[@]}" "${server_proxy_hosts[@]}" "${server_ports[@]}" | cut -d ':' -f 1 | sort -u); do
    name_value=$(printf "%s\n" "${server_names[@]}" | grep "^$key:" | cut -d ':' -f 2-)
    proxy_value=$(printf "%s\n" "${server_proxy_hosts[@]}" | grep "^$key:" | cut -d ':' -f 2-)
    port_value=$(printf "%s\n" "${server_ports[@]}" | grep "^$key:" | cut -d ':' -f 2-)
    if [[ -n $name_value && -n $proxy_value ]]; then
        port_value=${port_value:-$default_port}
        valid_groups+=("$key:$name_value,$proxy_value,$port_value")
    fi
done

# 如果没有有效分组，退出
if [ ${#valid_groups[@]} -eq 0 ]; then
    echo "No valid groups found. Exiting..."
    exit 1
fi

# 输出路径
output_path=${OUTPUT_PATH:-/etc/nginx/conf.d/default.conf}

# 创建 Nginx 配置文件
cat <<EOF > "$output_path"
server_tokens off;
EOF

# 日志格式配置
if [ "$log_format" = "json" ]; then
    cat <<EOF >> "$output_path"
log_format custom_log_format escape=json '{'
        '"remote_addr": "\$remote_addr", '
        '"request_uri": "\$request_uri", '
        '"request_length": "\$request_length", '
        '"request_time": "\$request_time", '
        '"request_method": "\$request_method", '
        '"status": "\$status", '
        '"body_bytes_sent": "\$body_bytes_sent", '
        '"http_referer": "\$http_referer", '
        '"http_user_agent": "\$http_user_agent", '
        '"http_x_forwarded_for": "\$http_x_forwarded_for", '
        '"http_host": "\$http_host", '
        '"server_name": "\$server_name", '
        '"upstream": "\$upstream_addr", '
        '"upstream_response_time": "\$upstream_response_time"'
        '}';
EOF
else
    cat <<EOF >> "$output_path"
log_format custom_log_format '\$remote_addr - \$remote_user [\$time_local] "\$request" '
        '\$status \$body_bytes_sent "\$http_user_agent" "\$upstream_addr" "\$request_time"';
EOF
fi

# 写入每个 server 块
for group in "${valid_groups[@]}"; do
    key=${group%%:*}
    name_value=${group#*:}
    server_name=${name_value%%,*}
    remaining=${name_value#*,}
    proxy_host=${remaining%,*}
    port=${remaining##*,}

    echo "start generate $key"

    # 写入 server 块
    cat <<EOF >> "$output_path"

server {
    listen ${port}$( [ "$open_ssl" = "true" ] && echo " ssl" );
    server_name ${server_name};

$( [ "$open_ssl" = "true" ] && cat <<SSL
    ssl_certificate      /etc/nginx/ssl/${server_name}.pem;
    ssl_certificate_key  /etc/nginx/ssl/${server_name}.key;

    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
SSL
)

    location / {
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;

        client_max_body_size 100m;
        client_body_buffer_size 100m;
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
        proxy_read_timeout 300s;
        proxy_buffer_size 256k;
        proxy_buffers 4 256k;
        proxy_busy_buffers_size 256k;

        proxy_pass ${proxy_host};
    }
}
EOF
    echo "generate $key success"
done

if [ "$enable_health_check" = "true" ]; then
# 添加默认的server块
cat <<EOF >> "$output_path"
    server {
        listen       80;
        server_name  _;

        root   /usr/share/nginx/html;
        index  index.html index.htm;

        location / {
            try_files $uri $uri/ =404;
        }
    }
EOF
fi

echo "Nginx configuration generated successfully at $output_path"